import pandas as pd
import numpy as np
import pyecharts.options as opts
from pyecharts.charts import Line,Bar,Tab,Page,Grid
import datetime


# 画图
def makeline(tt,x,y1,y2,y3):
    ln=Line()
    ln.add_xaxis(xaxis_data=x)

    ln.add_yaxis(
            series_name="注册",     # 系列名称，""时不显示图例
            y_axis = y1,
            symbol="emptyCircle",
            is_symbol_show=True,
            label_opts=opts.LabelOpts(is_show=False),
        )

    ln.add_yaxis(
            series_name="开户",     # 系列名称，""时不显示图例
            y_axis = y2,
            symbol="emptyCircle",
            is_symbol_show=True,
            label_opts=opts.LabelOpts(is_show=False),
        )

    ln.add_yaxis(
            series_name="首入金",     # 系列名称，""时不显示图例
            y_axis = y3,
            symbol="emptyCircle",
            is_symbol_show=True,
            label_opts=opts.LabelOpts(is_show=False),
        )
    ln.set_global_opts(
        title_opts=opts.TitleOpts(title=tt),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
#         toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
        legend_opts=opts.LegendOpts(type_="scroll", pos_left="right", pos_top="top"),
    )
    return ln


# 获取数据的x,y数值
def getxy(dd):
    y1 = dd[dd['指标']=='注册']['人数']
    y2 = dd[dd['指标']=='开户']['人数']
    y3 = dd[dd['指标']=='首入金']['人数']

    x = dd['月份'].map(str).unique().tolist()
    x.sort(reverse=False)
    return x,y1,y2,y3



if __name__ == '__main__':

    td=datetime.datetime.today().strftime('%m%d')

    file_dir='E:/项目/零碎/'
    data_file = '20211129-091101.csv'

    #读取数据
    org_data= pd.read_csv(file_dir+data_file)

    # 获取一二级部门的名单
    l1_list = org_data['一级部门'].unique().tolist()
    l2_dict = {}
    for i in l1_list:
        l2_dict[i]=org_data[org_data['一级部门']== i ]['二级渠道'].unique().tolist()

    # 统计一级部门的数值
    lv1_data = org_data.groupby(['指标','月份','一级部门']).sum()
    lv1_data.reset_index(inplace=True)

    # 开始画图
    page = Page(page_title='分周获客'+td,layout=Page.DraggablePageLayout)

    for i in l1_list:
        t1 = lv1_data[lv1_data['一级部门']==i]
        x,y1,y2,y3 = getxy(t1)
        ln = makeline(i,x,y1,y2,y3)
        ln.chart_id = 'lv1_'+i.replace('-','_')
        page.add(ln)
        for j in l2_dict[i]:
            if j not in ['CTS-王宝峰','PRO-郑航']:
                t2 = org_data[org_data['二级渠道']==j]
                x,y1,y2,y3 = getxy(t2)
                ln = makeline(j,x,y1,y2,y3)
                ln.chart_id = 'lv2_'+j.replace('-','_')
                page.add(ln)

    # 生成可拖动未排版的图表
    page.render(file_dir+'page_unfinished.html')
    
    # 手动调整图表大小和位置进行排版
    # 输出config并调整坐标
    
    # 重新排版
    page.save_resize_html(file_dir+"page_unfinished.html", cfg_file=file_dir+"huoke_config.json", dest=file_dir+'获客'+td+'.html')
    print('done')
